import os
from functools import partial
from datetime import datetime

from django.db import models
from django.utils import timezone


def upload_file_rename(path):
    return partial(wrapper, path=path)


def wrapper(instance, filename, path):
    now = datetime.now()
    parent = '%s/%d/%d/%d' % (path, now.year, now.month, now.day)
    filename = '%d-%s' % (int(datetime.now().timestamp()), filename)
    return os.path.join(parent, filename)


class ServerApplication(models.Model):
    user_id = models.CharField(verbose_name='申请人工号', max_length=100)
    user_name = models.CharField(verbose_name='申请人姓名', max_length=100)
    user_email = models.EmailField(verbose_name='申请人邮件')
    project_name = models.CharField(verbose_name='项目名', max_length=200, default='')
    server_count = models.IntegerField(verbose_name='申请服务器总数量',  default=0)
    budget = models.IntegerField(verbose_name='大致预算', default=0)
    detail_file = models.FileField(verbose_name='详细附件', upload_to=upload_file_rename('server'))
    remark = models.TextField(verbose_name='备注', default='')
    pub_date = models.DateTimeField(verbose_name='申请时间', default=timezone.now)

    def __str__(self):
        return '%s-%s' % (self.user_name, self.project_name)


class Approval(models.Model):
    server_application = models.ForeignKey(ServerApplication, on_delete=models.CASCADE)
    approver_name = models.CharField(verbose_name='审批人姓名', max_length=100)
    approver_respectful_name = models.CharField(verbose_name='审批人尊称', max_length=100, blank=True, default='')
    approver_email = models.EmailField(verbose_name='审批人邮件')
    result = models.NullBooleanField(verbose_name='审批结果', max_length=100)
    pub_date = models.DateTimeField(verbose_name='审批时间', default=timezone.now)

    def __str__(self):
        if self.approver_respectful_name:
            return '%s-%s' % (self.approver_respectful_name, self.result)
        else:
            return '%s-%s' % (self.approver_name, self.result)
